import cv2
# 加载视频
cap = cv2.VideoCapture()
cap.open(r'C:\OpenCV\data\vtest.avi')
if not cap.isOpened():
    print("无法打开视频文件")
pBgModel = cv2.createBackgroundSubtractorMOG2()

def labelTargets(img, mask, threshold):
    seg = mask.copy()
    cnts = cv2.findContours(seg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    count = 0
    for i in cnts[1]:
        area = cv2.contourArea(i)
        if area < threshold:
            continue
        count += 1
        rect = cv2.boundingRect(i)
        print("矩形：X:{} Y:{} 宽：{} 高：{}".format(rect[0], rect[1], rect[2], rect[3]))
        cv2.drawContours(img, [i], -1, (255, 255, 0), 1)
        cv2.rectangle(img, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 0, 255), 1)
        cv2.putText(img, str(count), (rect[0], rect[1]), cv2.FONT_HERSHEY_PLAIN, 0.5, (0, 255, 0))
    return count

while True:
    flag, source = cap.read()
    if not flag:
        break
    image = cv2.pyrDown(source)

    fgMask = pBgModel.apply(image)

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    morphImage_open = cv2.morphologyEx(fgMask, cv2.MORPH_OPEN, kernel, iterations=5)
    mask = fgMask - morphImage_open
    _, Mask = cv2.threshold(mask, 30, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # Mask = cv2.GaussianBlur(Mask, (5, 5), 0)
    targets = labelTargets(image, Mask, 30)
    cv2.imshow("check result pic",  image)


    print("共检测%s个目标" % targets)
    backGround = pBgModel.getBackgroundImage()
    foreGround = image - backGround

    key = cv2.waitKey(10)
    if key == 27:
        break
